package com.dex4d.ui.main.adapter;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.glide.GlideUtil;
import com.dex4d.ui.main.activity.D4DTransactionActivity;
import com.dex4d.ui.main.activity.TradeActivity;
import com.dex4d.ui.main.activity.WithdrawActivity;
import com.dex4d.ui.main.model.AccountModel;
import com.dex4d.ui.main.model.CoinToken;
import com.dex4d.ui.main.model.HomeModel;
import com.dex4d.ui.main.model.TokenDetail;
import com.dex4d.ui.main.model.TokenGame;
import com.dex4d.utils.BalanceUtils;
import com.yqritc.recyclerviewflexibledivider.FlexibleDividerDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者    LiQingyi
 * 时间    2018/10/31 16:03
 * 文件    dex4d-android
 * 描述
 */
public class AccountAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
        implements FlexibleDividerDecoration.VisibilityProvider {

    private static final int HEAD_TYPE = 0;
    private static final int COIN_TYPE = 1;

    private List<AccountModel> list;
    private Activity activity;
    private LayoutInflater inflater;
    private Map<String, CoinToken> tokenMap;
    private Map<String, TokenDetail> tokenDetailMap;

    public AccountAdapter(Activity activity, HomeModel model) {
        this.activity = activity;
        this.inflater = LayoutInflater.from(activity);
        this.list = new ArrayList<>();
        this.tokenMap = new HashMap<>();
        AccountModel accountModel = new AccountModel(HEAD_TYPE);
        accountModel.totalDex4DBalance = model.totalDex4DBalance;
        accountModel.totalTokenBalance = model.totalTokenBalance;
        this.list.add(accountModel);

        tokenDetailMap = new HashMap<>();
        if (model.tokenDetailList != null && !model.tokenDetailList.isEmpty()) {
            for (TokenDetail d : model.tokenDetailList) {
                tokenDetailMap.put(d.symbol, d);
            }
        }

    }

    public void updateTopData() {

    }

    /**
     * 更新数据
     *
     * @param tokenList
     */
    public void updateItemData(List<CoinToken> tokenList) {

        if (tokenList == null || tokenList.isEmpty())
            return;

        if (this.list.size() > 1) {//数据刷新时需要清除出第一条之外的所有信息
            removeToken(list);
        }

        int size = tokenList.size();
        for (int i = 0; i < size; i++) {
            CoinToken temp = tokenList.get(i);
            temp.pos = i + 1;
            this.list.add(new AccountModel(COIN_TYPE, temp));
            this.tokenMap.put(temp.symbol, temp);
        }

        notifyDataSetChanged();
    }

    //Iterator
    private List<AccountModel> removeToken(List<AccountModel> input) {
        Iterator<AccountModel> modelIterator = input.iterator();
        while (modelIterator.hasNext()) {
            AccountModel model = modelIterator.next();
            if (model.type == COIN_TYPE) {
                modelIterator.remove();
            }
        }
        return input;
    }


    /**
     * 更新游戏列表
     *
     * @param gameList
     */
    public void updateItemGame(List<TokenGame> gameList) {
        if (gameList == null || gameList.isEmpty()) {
            return;
        }
        String symbol = gameList.get(0).token_name;
        CoinToken coinToken = this.tokenMap.get(symbol);
        if (coinToken != null) {
            coinToken.tokenGames = gameList;
            notifyItemChanged(coinToken.pos, new PayLoad(PayLoad.LOAD_GAME));
        }
    }

    /**
     * 更新订单状态信息
     *
     * @param symbol
     * @param pending
     */
    public void updatePending(String symbol, int pending) {
        CoinToken coinToken = this.tokenMap.get(symbol);
        if (coinToken != null) {
            coinToken.pending = pending;
            notifyItemChanged(coinToken.pos, new PayLoad(PayLoad.LOAD_PENDING));
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int pos) {
        int type = getItemViewType(pos);
        if (type == HEAD_TYPE) {
            View view = inflater.inflate(R.layout.acount_item_rv_total, viewGroup, false);
            return new HeadHolder(view);
        } else {
            View view = inflater.inflate(R.layout.acount_item_rv_trade, viewGroup, false);
            return new CoinHolder(view);
        }
    }

    //获取所有交易池--提现、对倒均可使用
    public ArrayList<CoinToken> getAllCoinTokens(){
        ArrayList<CoinToken> tokenList = new ArrayList<CoinToken>();
        for(AccountModel accountModel:list){
            if(accountModel.coinToken!=null){
                tokenList.add(accountModel.coinToken);
            }
        }
        return tokenList;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int pos) {
        AccountModel model = list.get(pos);
        if (viewHolder instanceof CoinHolder) {
            CoinHolder holder = (CoinHolder) viewHolder;
            final CoinToken token = model.coinToken;

            holder.btnTrade.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TradeActivity.start(activity, token, tokenDetailMap.get(token.symbol),getAllCoinTokens());
                }
            });
            holder.txt_coin_name.setText(token.getShowSymbol());
            GlideUtil.displayImg(holder.img_coin, token.logo);
            holder.txt_trade_dex.setText(BalanceUtils.format(token.dex4d));
            holder.txt_trade_token.setText(BalanceUtils.format(token.coins));
            holder.txt_trade_txs.setText(BalanceUtils.format(token.dividends));
            holder.txt_trade_ref.setText(BalanceUtils.format(token.rebateFees));
            holder.txt_pending.setText(token.getPending(activity));
            updateGameUI(holder, token);
        } else if (viewHolder instanceof HeadHolder) {
            HeadHolder vh = (HeadHolder) viewHolder;
            vh.txt_total_balance.setText(BalanceUtils.format(model.totalTokenBalance));
            vh.txt_total_4d.setText(BalanceUtils.format(model.totalDex4DBalance));
            vh.btn_withdraw.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WithdrawActivity.start(activity,getAllCoinTokens());
                }
            });
            vh.btn_history.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((AppToolBarBaseActivity)activity).openActivity(D4DTransactionActivity.class);
                }
            });
        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads.isEmpty()) {//全局刷新
            onBindViewHolder(holder, position);
        } else {//局部刷新
            Object obj = payloads.get(0);
            if (obj instanceof PayLoad && holder instanceof CoinHolder) {

                PayLoad load = (PayLoad) obj;
                CoinHolder vh = (CoinHolder) holder;
                AccountModel model = list.get(position);
                CoinToken coinToken = model.coinToken;

                if (load.flag == PayLoad.LOAD_GAME) {//TODO 底部游戏数据加载
                    updateGameUI(vh, coinToken);
                } else if (load.flag == PayLoad.LOAD_PENDING) {//TODO 订单状态
                    vh.txt_pending.setText(coinToken.getPending(activity));
                } else { //TODO 订单状态数据刷新

                }
            }
        }
    }

    private void updateGameUI(CoinHolder vh, CoinToken coinToken) {
        if (coinToken.tokenGames == null || coinToken.tokenGames.isEmpty())
            return;
        TokenGameAdapter gameAdapter = new TokenGameAdapter(activity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        vh.rv_game.setLayoutManager(layoutManager);
        vh.rv_game.setAdapter(gameAdapter);
        gameAdapter.addData(coinToken.tokenGames);
    }

    @Override
    public int getItemViewType(int position) {
        AccountModel model = list.get(position);
        return model.type;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public boolean shouldHideDivider(int position, RecyclerView parent) {
        return position < 1;
    }

    static class HeadHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.txt_total_balance)
        TextView txt_total_balance;

        @BindView(R.id.txt_total_4d)
        TextView txt_total_4d;

        @BindView(R.id.btn_withdraw)
        LinearLayout btn_withdraw;

        @BindView(R.id.btn_history)
        LinearLayout btn_history;

        HeadHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class CoinHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.img_coin)
        ImageView img_coin;

        @BindView(R.id.txt_coin_name)
        TextView txt_coin_name;

        @BindView(R.id.btn_trade)
        Button btnTrade;

        @BindView(R.id.txt_trade_dex)
        TextView txt_trade_dex;

        @BindView(R.id.txt_trade_token)
        TextView txt_trade_token;

        @BindView(R.id.txt_trade_txs)
        TextView txt_trade_txs;

        @BindView(R.id.txt_trade_ref)
        TextView txt_trade_ref;

        @BindView(R.id.txt_account_pending)
        TextView txt_pending;

        @BindView(R.id.rv_game)
        RecyclerView rv_game;

        CoinHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class PayLoad {
        static final int LOAD_DEF = 0;//更新局部数据
        static final int LOAD_GAME = 1;//加载游戏列表
        static final int LOAD_PENDING = 2;//更新订单状态
        int flag;

        public PayLoad() {
            this.flag = LOAD_DEF;
        }

        PayLoad(int flag) {
            this.flag = flag;
        }
    }
}
